package org.dromara.learning_xq.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.dromara.learning_xq.entity.AsChapterContent;
import org.dromara.learning_xq.mapper.AsChapterContentMapper;
import org.dromara.learning_xq.service.AsChapterContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class AsChapterContentServiceimpl extends ServiceImpl<AsChapterContentMapper, AsChapterContent> implements AsChapterContentService {

    @Autowired
    private AsChapterContentMapper asChapterContentMapper;


    /**
     * 批量插入章节目录内容
     * <p>
     * 本方法重写插入操作，以支持批量插入。通过直接调用底层提供的批量保存方法，提高了数据插入效率，适用于需要大量插入操作的场景
     *
     * @param asChapterContentList 待插入的章节目录内容列表
     * @return 批量插入操作是否成功
     */
    @Override
    public boolean insertAsChapterContent(List<AsChapterContent> asChapterContentList) {
        return this.saveBatch(asChapterContentList);
    }


    @Override
    public boolean updateAsChapterContent(AsChapterContent asChapterContent) {
        return this.updateById(asChapterContent);
    }

    @Override
    public AsChapterContent getTree() {
        List<AsChapterContent> allNodes = asChapterContentMapper.selectList(null);

        // 使用 Map 来存储所有节点
        Map<Long, AsChapterContent> nodeMap = allNodes.stream()
            .collect(Collectors.toMap(AsChapterContent::getId, node -> node));

        AsChapterContent root = null;

        // 遍历所有节点，设置子节点
        for (AsChapterContent node : allNodes) {
            Long parentId = node.getPId();
            if (parentId == 0) {
                root = node;
            } else {
                AsChapterContent parentNode = nodeMap.get(parentId);
                if (parentNode != null) {
                    if (parentNode.getChildren() == null) {
                        parentNode.setChildren(new ArrayList<>());
                    }
                    parentNode.getChildren().add(node);
                }
            }
        }

        return root;
    }
}
